﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using XNATools.Managers;
using XNATools.Diagnostics;
using XNATools.Enums;
using XNATools.Services;
using XNATools.Events.EventArgs;
using XNATools.Engine2D;
using TestLibrairies;
using XNATools.Events;
using XNATools;

namespace Demo2D
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class GameMain : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        CachedContentManager<Texture2D> TextureCache;
        InputManager InputManager;
        List<Brick> bricks = new List<Brick>();
        Ball ball;
        Bat bat;
        int bricksInWidth = 6;
        int bricksInHeight = 3;

        public GameMain()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            ServiceManager.Game = this; // /!\-> Don't forget to set Game properties of ServiceManager
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            //Add SpriteBatch to Services. This allow SpriteBatch to be available from ServiceManager
            ServiceManager.AddSpriteBatch(new SpriteBatch(GraphicsDevice));

            //Basic initilizations
            ScreenManager.GraphicsDeviceManager = graphics;
            ScreenManager.ChangeResolution(800, 600);
            ScreenManager.DebugFrame = new DebugFrame(this, Vector2.Zero, FrameDisplay.All, Color.Black);

            ScreenManager.DebugFrame.AddDebugObject("Mouse");
            ScreenManager.DebugFrame.AddDebugObject("Screen");
            ScreenManager.DebugFrame.AddDebugObjectData("Screen", string.Format("Screen size: Width: {0}, Height:{1}; Keep ratio: {2}", Window.ClientBounds.Width, Window.ClientBounds.Height, ScreenManager.KeepAspectRatio));

            //Create a cache for all Texture2D
            TextureCache = new CachedContentManager<Texture2D>(this, "Textures", true);
            //Create an InputManager an initialise input services
            InputManager = new InputManager(this);
            KeyboardService kService = new KeyboardService(this);
            MouseService mService = new MouseService(this);
            InputManager.KeyboardAction += new KeyboardActionEventHandler(InputManager_KeyboardAction);
            InputManager.MouseMove += new MouseActionEventHandler(InputManager_MouseMove);

            //Initialize background
            Background background = new Background(this, "Textures\\grass");
            //Initialize elements
            ball = new Ball(this);
            bat = new Bat(this);

            IsMouseVisible = true;

            for (int i = 0; i < bricksInWidth * bricksInHeight; i++)
            {
                bricks.Add(new Brick(this));
            }

            base.Initialize();
        }

        private void InputManager_MouseMove(object sender, MouseActionEventArgs e)
        {
            ScreenManager.DebugFrame["Mouse"] = e.MouseService.Position.ToString();
        }

        private void InputManager_KeyboardAction(object sender, KeyboardActionEventArgs e)
        {
            if (e.KeyboardService.IsKeyDown(Keys.Escape))
            {
                this.Exit();
            }
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            Vector2 basePosition = new Vector2(ScreenManager.ScreenCenter.X - bricksInWidth / 2 * bricks[0].Bounds.Width, 0);
            for (int i = 0; i < bricksInHeight; i++)
            {
                for (int j = 0; j < bricksInWidth; j++)
                {
                    bricks[i * bricksInWidth + j].Position = basePosition;
                    basePosition.X += bricks[0].Bounds.Width;
                }
                basePosition.X = ScreenManager.ScreenCenter.X - bricksInWidth / 2 * bricks[0].Bounds.Width;
                basePosition.Y += bricks[0].Bounds.Height;
            }
            
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {

        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            //Very fast collision detection :p
            Brick toRemove = null;            
            foreach (Brick b in bricks)
            {
                if (b.Intersects(ball))
                {
                    toRemove = b;
                    Components.Remove(b);
                    ball.Direction *= -1;
                }
            }
            if (toRemove != null)
                bricks.Remove(toRemove);

            if (ball.Intersects(bat))
            {
                ball.Direction.Y *= -1;
            }

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            ServiceManager.Get<SpriteBatch>().Begin();

            base.Draw(gameTime);

            ServiceManager.Get<SpriteBatch>().End();
        }
    }
}
